package com.review.Test;

import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

public class MyQueue {

	private LinkedList<Object> list = new LinkedList<>();

	private AtomicInteger count = new AtomicInteger(0);

	private final int MAXSIZE;

	private final int MINSIZE = 0;

	public MyQueue(int max){
		this.MAXSIZE = max;
	}

	public synchronized void put(Object obj) throws InterruptedException{
		while (count.get() == this.MAXSIZE) {
			this.wait();
		}

		list.add(obj);
		count.incrementAndGet();
		this.notify();
	}

	public synchronized Object take() throws InterruptedException{
		Object obj = null;
		while (count.get() == this.MINSIZE) {
			this.wait();
		}
		obj = list.removeFirst();
		count.decrementAndGet();
		this.notify();

		return obj;
	}

	public int getSize(){
		return list.size();
	}

	public static void main(String[] args) throws InterruptedException {

		final MyQueue myQueue = new MyQueue(3);
		myQueue.put("a");
		myQueue.put("b");
		myQueue.put("c");


		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					myQueue.put("d");
					myQueue.put("e");
					System.out.println("新增完毕");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}, "t1");
		
		t1.start();
		System.out.println("此时size"+myQueue.getSize());
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Object o1 = myQueue.take();
					System.out.println("移除:"+o1);
					Object o2 = myQueue.take();
					System.out.println("移除:"+o2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}, "t2");
		
		Thread.sleep(3000);
		
		t2.start();
	}

}
